"""
Booking schemas for request/response validation.
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional
from datetime import datetime
from uuid import UUID
from app.models.booking import BookingStatus


class BookingBase(BaseModel):
    """Base booking schema."""
    room_id: UUID
    booking_person: str = Field(..., min_length=1, max_length=100)
    meeting_content: str = Field(..., min_length=1)
    start_time: datetime
    end_time: datetime
    
    @field_validator('end_time')
    @classmethod
    def validate_end_time(cls, v, info):
        """Validate that end_time is after start_time."""
        if 'start_time' in info.data and v <= info.data['start_time']:
            raise ValueError('end_time must be after start_time')
        return v


class BookingCreate(BookingBase):
    """Schema for creating a new booking."""
    pass


class BookingUpdate(BaseModel):
    """Schema for updating booking information."""
    booking_person: Optional[str] = Field(None, min_length=1, max_length=100)
    meeting_content: Optional[str] = Field(None, min_length=1)
    start_time: Optional[datetime] = None
    end_time: Optional[datetime] = None
    status: Optional[BookingStatus] = None


class BookingInDB(BookingBase):
    """Schema for booking in database."""
    id: UUID
    status: BookingStatus
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class BookingResponse(BaseModel):
    """Schema for booking response with room details."""
    id: UUID
    room_id: UUID
    booking_person: str
    meeting_content: str
    start_time: datetime
    end_time: datetime
    status: BookingStatus
    created_at: datetime
    room_name: Optional[str] = None
    
    class Config:
        from_attributes = True
        
    @classmethod
    def from_orm(cls, obj):
        """Create BookingResponse from ORM object with room name."""
        data = {
            "id": obj.id,
            "room_id": obj.room_id,
            "booking_person": obj.booking_person,
            "meeting_content": obj.meeting_content,
            "start_time": obj.start_time,
            "end_time": obj.end_time,
            "status": obj.status,
            "created_at": obj.created_at,
            "room_name": obj.room.name if obj.room else None
        }
        return cls(**data)


class CheckAvailabilityRequest(BaseModel):
    """Schema for checking room availability."""
    room_id: UUID
    start_time: datetime
    end_time: datetime
    exclude_booking_id: Optional[UUID] = None  # For update scenarios


class CheckAvailabilityResponse(BaseModel):
    """Schema for availability check response."""
    available: bool
    conflicting_bookings: Optional[list] = []
    message: str